//
//  FSNewReceiveDetailController.m
//  WZSOA
//
//  Created by 刘沿 on 16/6/8.
//  Copyright © 3016年 刘沿. All rights reserved.
//

#import "FSNewReceiveDetailController.h"
#import <QuickLook/QuickLook.h>
#import "GDataDefines.h"
@interface FSNewReceiveDetailController ()<UITableViewDataSource,UITableViewDelegate,UIWebViewDelegate,QLPreviewControllerDataSource,QLPreviewControllerDelegate>

@property(nonatomic,strong)FSReceiveDetailModel * detailModel;
@property(nonatomic,strong)NSMutableArray * attachmentArray;
@property(nonatomic,strong)NSString * attacmentURL;
@end

@implementation FSNewReceiveDetailController

-(NSMutableArray*)attachmentArray{
    if (_attachmentArray ==nil) {
        _attachmentArray = [NSMutableArray array];
    }
    return _attachmentArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"详情";
    
    self.tableView.hidden = YES;

    [self loadData];
}

#pragma mark 加载网络数据
-(void)loadData{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    NSArray *array = nil;
    
    NSString *method = nil;
    
    NSString *url = nil;
    
    if (self.type == newReceive) {
        
        NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
        array = @[@{@"unId":self.fileId},@{@"userId":userId}];
        
        url = KexchgeneralURL;
        
        method = KContentInMethod;
    }else if(self.type == ProfileSear){
    
        NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
        
        array = @[@{@"userId":userId},@{@"unId":self.fileId},@{@"dbpath":self.dbpath}];
        
        url = Kexcharchive;
    
        method = KgetArichiveDoc;
        
    }else {
    
        NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
        
        array = @[@{@"unid":self.unid},@{@"userId":userId}];
        
        url = Kexchlogistics;
    
        method = KcontentMeet;
    }
    
    [HttpTools postWithURL:url arrays:array method:method success:^(id JSON) {
    
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        self.tableView.hidden = NO;
        self.detailModel = [self getDetailModel:JSON];
        [self.tableView reloadData];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refrshData" object:nil];
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }];
    
}

-(FSReceiveDetailModel*)getDetailModel:(id)json{
    NSData * data = [json dataUsingEncoding:NSUTF8StringEncoding];
    FSReceiveDetailModel * detailModel = [[FSReceiveDetailModel alloc]init];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点（Users）
    GDataXMLElement *rootElement = [doc rootElement];
    //获取根节点下的节点（User）
    
    if (self.type == newReceive) {
        
        NSArray *rootData= [rootElement elementsForName:@"数据"];
        for (GDataXMLElement *subData in rootData) {
            GDataXMLElement *documentElement= [[subData elementsForName:@"文档"] objectAtIndex:0];
            detailModel.document = [documentElement stringValue];

        }
        
        for (GDataXMLElement * subData in rootData) {
            NSArray * tempArray = [subData elementsForName:@"正文实体"];
            for (GDataXMLElement * element in tempArray) {
                NSArray *array = [element elementsForName:@"附件"];
                for (GDataXMLElement * data in array) {
                    FSAttachmentModel * attachModel = [[FSAttachmentModel alloc]init];
                    GDataXMLElement * nameElement = [[data elementsForName:@"名称"] objectAtIndex:0];
                    NSString *  name = [nameElement stringValue];
                    attachModel.attachmentsTitle = name;
                    
                    GDataXMLElement * contentElement = [[data elementsForName:@"内容"] objectAtIndex:0];
                    NSString *  content = [contentElement stringValue];
                    attachModel.attachmentsURL = content;
                    
                    [self.attachmentArray addObject:attachModel];
                }
            }
        }
        
        return detailModel;
        
    }else if(self.type == ProfileSear){
        NSArray *rootData= [rootElement elementsForName:@"数据"];
        for (GDataXMLElement *subData in rootData) {
             NSArray * tempArray = [subData elementsForName:@"数据要素"];
            for (GDataXMLElement *data in tempArray) {
               GDataXMLElement *documentElement= [[data elementsForName:@"文档"] objectAtIndex:0];
               detailModel.document = [documentElement stringValue];
            
               GDataXMLElement *filestep= [[data elementsForName:@"填写意见环节"] objectAtIndex:0];
               detailModel.setp = [filestep stringValue];
            
               GDataXMLElement *fileId= [[data elementsForName:@"唯一标识"] objectAtIndex:0];
               detailModel.fileId = [fileId stringValue];
            
             }
        }
        
            for (GDataXMLElement * subData in rootData) {
                NSArray * tempArray = [subData elementsForName:@"数据实体"];
                for (GDataXMLElement * element in tempArray) {
                    NSArray *array = [element elementsForName:@"附件"];
                    for (GDataXMLElement * data in array) {
                        FSAttachmentModel * attachModel = [[FSAttachmentModel alloc]init];
                        GDataXMLElement * nameElement = [[data elementsForName:@"名称"] objectAtIndex:0];
                        NSString *  name = [nameElement stringValue];
                        attachModel.attachmentsTitle = name;
        
                        GDataXMLElement * contentElement = [[data elementsForName:@"内容"] objectAtIndex:0];
                        NSString *  content = [contentElement stringValue];
                        attachModel.attachmentsURL = content;
        
                        [self.attachmentArray addObject:attachModel];
                    }
                }
            }
        
        for (GDataXMLElement * subData in rootData) {
            NSArray * tempArray = [subData elementsForName:@"正文实体"];
            for (GDataXMLElement * element in tempArray) {
                NSArray *array = [element elementsForName:@"附件"];
                for (GDataXMLElement * data in array) {
                    FSAttachmentModel * attachModel = [[FSAttachmentModel alloc]init];
                    GDataXMLElement * nameElement = [[data elementsForName:@"名称"] objectAtIndex:0];
                    NSString *  name = [nameElement stringValue];
                    attachModel.attachmentsTitle = name;
                    
                    GDataXMLElement * contentElement = [[data elementsForName:@"内容"] objectAtIndex:0];
                    NSString *  content = [contentElement stringValue];
                    attachModel.attachmentsURL = content;
                    
                    [self.attachmentArray addObject:attachModel];
                }
            }
        }
        
        return detailModel;
    
    }else {
    
        NSArray *rootData= [rootElement elementsForName:@"数据"];
        for (GDataXMLElement *subData in rootData) {
            GDataXMLElement *documentElement= [[subData elementsForName:@"文档"] objectAtIndex:0];
            detailModel.document = [documentElement stringValue];
            
        }
        
        for (GDataXMLElement *subData in rootData) {
            
            NSArray * tempArray = [subData elementsForName:@"附件"];
            
            for (GDataXMLElement * element in tempArray) {

                FSAttachmentModel * attachModel = [[FSAttachmentModel alloc]init];
                GDataXMLElement * nameElement = [[element elementsForName:@"名称"] objectAtIndex:0];
                NSString *  name = [nameElement stringValue];
                attachModel.attachmentsTitle = name;
                
                GDataXMLElement * contentElement = [[element elementsForName:@"内容"] objectAtIndex:0];
                NSString *  content = [contentElement stringValue];
                attachModel.attachmentsURL = content;
                
                [self.attachmentArray addObject:attachModel];
                
            }
            
        }
        
        return detailModel;
    
    }
}

#pragma mark UITableView

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    switch (section) {
        case 0:
            return self.detailModel.formArray.count;
            break;
        case 1:
            return self.attachmentArray.count;
        default:
            return 1;
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 80;

}

#pragma mark UITbableViewCell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        FSNewSendDetailCell * cell = [FSNewSendDetailCell cellWihtTableView:tableView];
        
        NSString * allString = self.detailModel.formArray[indexPath.row];

        cell.allString = allString;
        
        return cell;
        
    }else{
        static NSString * cellIdentifier = @"cellId";
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
        FSAttachmentModel * model = self.attachmentArray[indexPath.row];
        cell.textLabel.text = model.attachmentsTitle;
        cell.textLabel.font = [UIFont systemFontOfSize:15];
        cell.textLabel.numberOfLines = 0;
        cell.textLabel.textColor = [UIColor colorWithRed:85/255.0 green:85/255.0  blue:85/255.0 alpha:1.0];
        return cell;
    }
    
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 1) { //下载附件 查看附件信息
        FSAttachmentModel * model = self.attachmentArray[indexPath.row];
        [self openFileURL:model.attachmentsURL];
    }
    
}

-(void)openFileURL:(NSString*)url{
    NSString * stringurl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    self.attacmentURL =  [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[url lastPathComponent]]; //附件路径
    if ([self isExtistFilePathWithFileName:[[NSURL URLWithString:stringurl] lastPathComponent]]) { //已经存在附件
        QLPreviewController *previewoCntroller = [[QLPreviewController alloc] init] ;
        previewoCntroller.delegate=self;
        previewoCntroller.dataSource=self;
        previewoCntroller.navigationItem.rightBarButtonItem=nil;
        [self.navigationController pushViewController: previewoCntroller animated:YES];
        
    }else{
        
        MBProgressHUD * hud  =  [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.labelText = @"下载中...";
        NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:stringurl]];
        [self.webView loadRequest:request];
    }
    
}

#pragma mark PreviewDataSource
//第一个方法是设定一组文档浏览的个数，会影响到在文档预览中的上/下一页。
-(NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller {
    return 1;
}
//第二个方法是指定文档预览的文件路径
-(id<QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index {
    
    return [NSURL fileURLWithPath:self.attacmentURL];
}

-(BOOL)isExtistFilePathWithFileName:(NSString*)fileName{
    NSString * file = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString * filePath = [file stringByAppendingPathComponent:fileName];
    NSFileManager * fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath] && fileName.length != 0) {
        return YES;
    }else{
        return NO;
    }
    
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSURL * requestedURL = [request URL];
    NSData * fileData = [[NSData alloc] initWithContentsOfURL:requestedURL];
    NSString * filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    [fileData writeToFile:[filePath stringByAppendingPathComponent:[requestedURL lastPathComponent]] atomically:YES];
    return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView{
    
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    QLPreviewController *previewoCntroller = [[QLPreviewController alloc] init] ;
    previewoCntroller.delegate=self;
    previewoCntroller.dataSource=self;
    [self.navigationController pushViewController: previewoCntroller animated:YES];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}



@end






















